# Contributor: Rasmus Thomsen <oss@cogitri.dev>
# Contributor: Jakub Jirutka <jakub@jirutka.cz>
# Contributor: Shiz <hi@shiz.me>
# Contributor: Jeizsm <jeizsm@gmail.com>
# Contributor: Ariadne Conill <ariadne@dereferenced.org>
# Contributor: Celeste <cielesti@protonmail.com>
# Contributor: omni <omni+alpine@hack.org>
# Maintainer: team/rust <alpine@ptrcnull.me>
pkgname=rust
pkgver=1.78.0
_llvmver=17
_bootver=1.77.0
pkgrel=0
pkgdesc="Rust Programming Language toolchain"
url="https://www.rust-lang.org/"
arch="all"
license="Apache-2.0 AND MIT"

# 'cc' is needed at runtime just for linking. Someday rustc might invoke
# the linker directly, and then we'll only need 'ld'.
# See: https://github.com/rust-lang/rust/issues/11937
depends="gcc musl-dev"

# * Rust is self-hosted, so you need rustc (and cargo) to build rustc...
#   The last revision of this abuild that does not depend on itself (uses
#   prebuilt rustc and cargo) is 2e6769eb39eaff3029d8298fc02856623c563cd8.
# * Don't add libgit2-dev into make dependencies. There's no compatibility
#   guarantees between libgit2-sys and arbitrary system libgit2 versions;
#   when system libgit2 is upgraded to a new minor version, it may break
#   cargo and since we need cargo to rebuild cargo... this already happened
#   several times. For this reason we build cargo with vendored libgit2.
makedepends_build="
	!libgit2-dev
	cargo-bootstrap>=$_bootver
	coreutils
	curl-dev
	file
	libssh2-dev
	llvm$_llvmver-dev
	llvm$_llvmver-test-utils
	openssl-dev
	python3
	rust-bootstrap>=$_bootver
	tar
	wasi-libc
	xz-dev
	zlib-dev
	"
makedepends_host="
	curl-dev
	libssh2-dev
	llvm$_llvmver-dev
	openssl-dev
	zlib-dev
	"

# XXX: This is a hack to allow this abuild to depend on itself. Adding "rust"
# to makedepends would not work, because abuild implicitly removes $pkgname
# and $subpackages from the abuild's dependencies.
provides="rust-bootstrap=$pkgver-r$pkgrel"
# This is needed for -src that contains some testing binaries.
options="!archcheck"

case "$CARCH" in
arm*|riscv64)
	# +crt-static still broken here, last checked with rust 1.75.0
	options="$options !check"
	;;
*)
	;;
esac

subpackages="
	$pkgname-dbg
	$pkgname-doc
	$pkgname-clippy
	$pkgname-gdb::noarch
	$pkgname-lldb::noarch
	$pkgname-src::noarch
	$pkgname-wasm
	cargo
	cargo-bash-completions:_cargo_bashcomp:noarch
	cargo-zsh-completion:_cargo_zshcomp:noarch
	cargo-doc:_cargo_doc:noarch
	rustfmt
	"
source="https://static.rust-lang.org/dist/rustc-$pkgver-src.tar.xz
	alpine-move-py-scripts-to-share.patch
	alpine-target.patch
	do-not-install-libunwind-source.patch
	gcc-eh-libunwind.patch
	install-template-shebang.patch
	musl-fix-linux_musl_base.patch
	need-rpath.patch
	need-ssp_nonshared.patch
	no-export-ld-library-path.patch
	revert-rustc_codegen_ssa-use-try_canonicalize-in-rpath.patch
	system-wasm-ld.patch

	0001-ci-Add-support-for-dist-loongarch64-musl.patch
	0002-Promote-loongarch64-unknown-linux-musl-to-Tier-2-wit.patch
	0003-vendor-libc-Add-support-for-loongarch64-linux-musl.patch
	0004-vendor-libc-0.2.151-Add-support-for-loongarch64-linu.patch
	0005-vendor-compiler_builtins-Add-support-for-loongarch64.patch
	0006-vendor-openssl-src-Add-support-for-loongarch64-linux.patch
	0007-Revert-loongarch-add-frecipe-and-relax-target-featur.patch

	check-rustc
	"
builddir="$srcdir/rustc-$pkgver-src"

# secfixes:
#   1.71.1-r0:
#     - CVE-2023-38497
#   1.66.1-r0:
#     - CVE-2022-46176
#   1.56.1-r0:
#     - CVE-2021-42574
#   1.52.1-r1:
#     - CVE-2021-29922
#   1.51.0-r2:
#     - CVE-2020-36323
#     - CVE-2021-31162
#   1.34.2-r0:
#     - CVE-2019-12083
#   1.26.0-r0:
#     - CVE-2019-16760

if [ -z "$BOOTSTRAP" ]; then
	makedepends_build="
		$makedepends_build
		patchelf
		"
	makedepends_host="
		$makedepends_host
		scudo-malloc
		"
fi

# We have to add new architectures in multiple steps:
# 1. Compile with the upstream triplets, compiling alpine's triplets in
# 2. Compile again, now with our triplets selected as build/target, now that
#    rustc knows about them
_build="$CBUILD"
_target="$CTARGET"

_rlibdir="usr/lib/rustlib/$_target/lib"
_sharedir="usr/share/rust"

ldpath="/$_rlibdir"

export OPENSSL_NO_VENDOR=1
export RUST_BACKTRACE=1

export gztool="$(command -v pigz || echo gzip)"

# this is useful for when we have to patch vendored projects
_clear_vendor_checksums() {
	sed -i 's/\("files":{\)[^}]*/\1/' vendor/$1/.cargo-checksum.json
}

_unpack_build_dist() {
	local distname="$1" destdir="$2" tarball=

	case "$distname" in
	rust-src)
		tarball="$builddir"/build/dist/rust-src-$pkgver.tar.gz
		;;
	rust-std-*)
		tarball="$builddir"/build/dist/rust-std-$pkgver-${distname#rust-std-*}.tar.gz
		;;
	*)
		tarball="$builddir"/build/dist/$distname-$pkgver-$_target.tar.gz
		;;
	esac

	tar -I "$gztool -d" -xf "$tarball" \
		-C "$destdir" --strip-components=2 \
		--exclude=manifest.in --no-same-owner
}

prepare() {
	default_prepare
	_clear_vendor_checksums libc
	_clear_vendor_checksums libc-0.2.151
	_clear_vendor_checksums compiler_builtins
	_clear_vendor_checksums openssl-src
}

build() {
	if [ "$_build" != "$_target" ]; then
		export PKG_CONFIG_ALLOW_CROSS=1
	fi

	# absolutely do not set these here, rust "knows" what it's doing
	unset CARGO_PROFILE_RELEASE_LTO
	unset CARGO_PROFILE_RELEASE_OPT_LEVEL
	unset CARGO_PROFILE_RELEASE_PANIC
	unset CARGO_PROFILE_RELEASE_CODEGEN_UNITS

	export CFLAGS="$CFLAGS -O2"
	export CXXFLAGS="$CXXFLAGS -O2"

	case "$CARCH" in
	riscv64)
		;;
	*)
		local lto=--set="rust.lto=thin"
		;;
	esac

	case "$CARCH" in
	aarch64|ppc64le|x86_64)
		# this doesn't build on s390x, but since it's only useful with rust-analyzer,
		# and we enable it on these arches only, just do that
		local rust_analyzer="rust-analyzer-proc-macro-srv,"
		;;
	*)
		local rust_analyzer=""
		;;
	esac

	local targets="$_target" extra_conf_opts=
	if subpackage_types_has wasm; then
		targets="$targets,wasm32-wasi,wasm32-unknown-unknown"
		extra_conf_opts='
			--set=target.wasm32-unknown-unknown.sanitizers=false
			--set=target.wasm32-unknown-unknown.profiler=false
			--set=target.wasm32-unknown-unknown.linker=lld
			--set=target.wasm32-wasi.sanitizers=false
			--set=target.wasm32-wasi.profiler=false
			--set=target.wasm32-wasi.wasi-root=/usr/share/wasi-sysroot
			'
	fi

	./configure \
		--build="$_build" \
		--host="$_target" \
		--target="$targets" \
		--prefix="/usr" \
		--release-channel="stable" \
		--enable-local-rust \
		--local-rust-root="/usr" \
		--llvm-root="/usr/lib/llvm$_llvmver" \
		--disable-docs \
		--enable-extended \
		--tools="cargo,clippy,src,${rust_analyzer}rustdoc,rustfmt,rust-demangler" \
		--enable-llvm-link-shared \
		--enable-option-checking \
		--enable-locked-deps \
		--enable-profiler \
		--enable-vendor \
		--dist-compression-formats=gz \
		--python="python3" \
		--set="rust.musl-root=/usr" \
		--set="rust.backtrace-on-ice=true" \
		--set="rust.codegen-units=1" \
		--set="rust.codegen-units-std=1" \
		--set="rust.deny-warnings=false" \
		--set="rust.parallel-compiler=false" \
		--set="rust.remap-debuginfo=true" \
		--set="rust.description=Alpine Linux $pkgver-r$pkgrel" \
		$lto \
		--set="target.$_target.llvm-config=/usr/lib/llvm$_llvmver/bin/llvm-config" \
		--set="target.$_target.musl-root=/usr" \
		--set="target.$_target.crt-static=false" \
		--set="target.$_target.cc=${CROSS_COMPILE}cc" \
		--set="target.$_target.cxx=${CROSS_COMPILE}c++" \
		--set="target.$_target.ar=${CROSS_COMPILE}ar" \
		--set="target.$_target.linker=${CROSS_COMPILE}cc" \
		--set="target.$_build.musl-root=/usr" \
		--set="target.$_build.crt-static=false" \
		--set="target.$_build.cc=cc" \
		--set="target.$_build.cxx=c++" \
		--set="target.$_build.ar=ar" \
		--set="target.$_build.linker=cc" \
		$extra_conf_opts

	python3 ./x.py dist --jobs ${JOBS:-2}
}

check() {
	# At this moment lib/rustlib/$CTARGET/lib does not contain a complete
	# copy of the .so libs from lib (they will be copied there during
	# 'x.py install'). Thus we must set LD_LIBRARY_PATH for tests to work.

	msg "Setting up test env..."

	mkdir -p "$builddir/test-rustc"

	_unpack_build_dist rustc "$builddir/test-rustc" &
	_unpack_build_dist rust-std "$builddir/test-rustc" &
	wait

	export LD_LIBRARY_PATH="$builddir/test-rustc/lib/rustlib/$CTARGET/lib"

	msg "Sanity checks..."
	"$srcdir"/check-rustc "$builddir"/test-rustc/bin/rustc

	# XXX: There's some problem with these tests, we will figure it out later.
	#	make check \
	#		LD_LIBRARY_PATH="$_stage0dir/lib" \
	#		VERBOSE=1

	# these rebuild the whole compiler which takes a long time
	# msg "Running tests for cargo..."
	# CFG_DISABLE_CROSS_TESTS=1 python3 ./x.py test --no-fail-fast src/tools/cargo

	unset LD_LIBRARY_PATH
}

package() {
	# merged into main package
	provides="$provides rust-stdlib=$pkgver-r$pkgrel"
	replaces="rust-stdlib"

	mkdir -p "$pkgdir/usr"

	cd "$pkgdir"

	_unpack_build_dist rustc "$pkgdir/usr" &
	_unpack_build_dist rust-std "$pkgdir/usr" &
	_unpack_build_dist rustc-dev "$pkgdir/usr" &
	_unpack_build_dist rust-src "$pkgdir/usr" &
	wait
	_unpack_build_dist cargo "$pkgdir/usr" &
	_unpack_build_dist clippy "$pkgdir/usr" &
	_unpack_build_dist rustfmt "$pkgdir/usr" &
	if subpackage_types_has wasm; then
		_unpack_build_dist rust-std-wasm32-unknown-unknown "$pkgdir/usr" &
		_unpack_build_dist rust-std-wasm32-wasi "$pkgdir/usr" &
	fi
	wait

	# We don't want to include stuff like rust-llvm-* tools, as we will use the
	# system tools.
	rm -f usr/lib/rustlib/"$_target"/bin/rust-llvm-*

	# Python scripts are noarch, so move them to /usr/share.
	# Requires move-py-scripts-to-share.patch to be applied.
	_mv usr/lib/rustlib/etc/*.py $_sharedir/etc/
	rmdir -p usr/lib/rustlib/etc 2>/dev/null || true

	_mv usr/etc/bash_completion.d/cargo usr/share/bash-completion/completions/
	rmdir -p usr/etc/bash_completion.d 2>/dev/null || true

	_mv usr/lib/rustlib/src/rust usr/src/
	ln -s ../../../src/rust usr/lib/rustlib/src/rust

	# Remove some clutter.
	cd "$pkgdir"/usr/lib/rustlib
	rm -f components install.log manifest-* rust-installer-version uninstall.sh
	if [ "$_build" != "$_target" ]; then
		rm -rf "$pkgdir"/usr/lib/rustlib/$_build
	fi

	# for some reason the tar archive gets some root-only files for rlibs
	find "$pkgdir"/usr/lib/rustlib -type f -perm -600 -exec chmod 0644 {} \+
	find "$pkgdir"/usr/lib/rustlib -type f -perm -700 -exec chmod 0755 {} \+

	if [ -z "$BOOTSTRAP" ]; then
		# link scudo to tools by default on architectures where it works well
		# this is roughly 20+% faster with no downside except slightly higher
		# memory use, but this is a compiler that already uses a ton of memory
		case "$CARCH" in
		arm*) ;;
		*)
			patchelf --add-needed libscudo.so \
				"$pkgdir"/usr/bin/cargo \
				"$pkgdir"/usr/bin/rustc \
				"$pkgdir"/usr/bin/rustdoc
			;;
		esac
	fi
}

wasm() {
	pkgdesc="WebAssembly targets for rust"
	depends="rust=$pkgver-r$pkgrel lld wasi-libc"

	amove usr/lib/rustlib/wasm32-*
}

analysis() {
	pkgdesc="Compiler analysis data for the Rust standard library"
	depends="$pkgname=$pkgver-r$pkgrel"

	amove $_rlibdir/../analysis
}

gdb() {
	pkgdesc="GDB pretty printers for Rust"
	depends="$pkgname=$pkgver-r$pkgrel gdb"

	amove usr/bin/rust-gdb*
	amove $_sharedir/etc/gdb_*.py
}

lldb() {
	pkgdesc="LLDB pretty printers for Rust"
	depends="$pkgname=$pkgver-r$pkgrel lldb py3-lldb"

	amove usr/bin/rust-lldb
	amove $_sharedir/etc/lldb_*.py
	amove usr/lib/rustlib/etc/lldb_commands
}

clippy() {
	pkgdesc="Lints to catch common mistakes and improve your Rust code"
	depends="$pkgname=$pkgver-r$pkgrel"

	amove usr/bin/cargo-clippy
	amove usr/bin/clippy-driver
}

src() {
	pkgdesc="$pkgdesc (source code)"
	depends="$pkgname=$pkgver-r$pkgrel"
	license="$license OFL-1.1 GPL-3.0-or-later GPL-3.0-with-GCC-exception CC-BY-SA-3.0 LGPL-3.0"

	amove usr/src
	amove usr/lib/rustlib/src
}

cargo() {
	pkgdesc="The Rust package manager"
	license="Apache-2.0 MIT UNLICENSE"
	depends="$pkgname=$pkgver-r$pkgrel"
	# XXX: See comment on top-level provides=.
	provides="cargo-bootstrap=$pkgver-r$pkgrel"

	amove usr/bin/cargo
}

rustfmt() {
	pkgdesc="Rust Code Formatter"
	license="Apache-2.0"
	depends="cargo=$pkgver-r$pkgrel"

	amove usr/bin/rustfmt
	amove usr/bin/cargo-fmt
}

_cargo_bashcomp() {
	default_bashcomp

	pkgdesc="Bash completions for cargo"
	license="Apache-2.0 MIT"
	install_if="cargo=$pkgver-r$pkgrel bash-completion"
}

_cargo_zshcomp() {
	default_zshcomp

	pkgdesc="ZSH completions for cargo"
	license="Apache-2.0 MIT"
	install_if="cargo=$pkgver-r$pkgrel zsh"
}

_cargo_doc() {
	pkgdesc="The Rust package manager (documentation)"
	license="Apache-2.0 MIT"
	install_if="docs cargo=$pkgver-r$pkgrel"

	# XXX: This is hackish!
	cd "$pkgdir"/../$pkgname-doc
	_mv usr/share/man/man1/cargo* "$subpkgdir"/usr/share/man/man1/
}

_mv() {
	local dest; for dest; do true; done  # get last argument
	mkdir -p "$dest"
	mv "$@"
}

sha512sums="
d2fb9881e28849d871fda71b1b51652be3839b3283f0d32163f258c5c707a9fb7b589da8dc03bca2fefee1abdd2b44a5f17e85d8c6df7bea119d1e8d22371941  rustc-1.78.0-src.tar.xz
9de9d7ad05584e3cafddedcac409a4605a1d67e82260220deb3efd965603ee3148062b081c0cd736e50d82daad3a723fb6a7493fdf4dddfe36288645425a7946  alpine-move-py-scripts-to-share.patch
a2675849426b2aecdcbf702fd3d8ba6fffaa69736105c5afa6109a55c25c9e795f7a99f4fff250e24dbf8783cea57c1655a41b5af1848a7221956245877866c5  alpine-target.patch
0d9e5ee4ebf647d3c44dc59b8991d330f2eb0cfa788768c5c9c5f5b57327c3a46b26e93641753a32335d0e3e76a0ab95bb6ad8279913b0c76c752624b139c5c1  do-not-install-libunwind-source.patch
cfdb3499fa6b3dea5ff7d3fd266ab0e34571fd48fa17c5e0f1467b8896087979555209dd256c50d357fdca1859feade9bf4c8f7b5cf003a16891350d0a34d00b  gcc-eh-libunwind.patch
b283d31cc8d6559aa639d44f776e97c2a1e0f23c717b6784e549861b881555bd467fa6023180866aae81a9a58c5f83e306940ee645f3c6733a1bdef6130036c9  install-template-shebang.patch
a32f3a9bcab771cce6be2ad936cd4edad3bb638f38da02e79c29cfed967eb0edcdf47ae892bbdd2959cebb5c74dee3fcc752dc2405f761d5c8ecc0021abb24a0  musl-fix-linux_musl_base.patch
f3051a7d67cf7937867d50a3169d391718d1d8a33f69066f08020df45e131076a811e9b9429e448460ff129bb2ebbf429b3cb5a4d05e188dace18f576a33562c  need-rpath.patch
c5a94cc3518f3dbefb2011d1c4267530062843262133332cff96db2e779d7f9b57bdab336c50b927b1c84855db4fa1ab8eb62098286746c8dcf50a779ce0202b  need-ssp_nonshared.patch
0688d21b59aa47867cf2a307bf997a996f14435a2931cdbbddcfe52c899f00d2676cdc67aeff2c4fbbc220fdb21d8405ec206e96aece93904a6541ba7438f649  no-export-ld-library-path.patch
74c0d14a68c2d7355f15ec3704d387556ad337e4991831e94951906d17aeb60387d20586a63cf6cdc62b46c60e1874340a250196ec2b3e75c268af1c41fae7e9  revert-rustc_codegen_ssa-use-try_canonicalize-in-rpath.patch
5216e083a1709b3ecbbdeaaaf0e112ec88e7534952fdadf834ce864b55768e15d7d181c14127d4ef39f66ca2a94dd40eddb2c4ab297081d75e5f3a09dcbcfa56  system-wasm-ld.patch
a776824a63752cd46bfe954985558502751f3a9e4cf70b46a3fd4513b188209b99e7c7b11e1998a89d2155a199b3b9f8ecc4389df4e8fc4b983a3d387a4fea06  0001-ci-Add-support-for-dist-loongarch64-musl.patch
2473d80908b936cefdd99cb3c7e56ec6c714af0ae6d606f5459bfbe2d3713ac9e11ea642a8481b224d6c89074386802eb005a8a9d666d6a597a0cbcd35a19af9  0002-Promote-loongarch64-unknown-linux-musl-to-Tier-2-wit.patch
6c4eee378995816f6da26bdea6c781e106be79ba9772d91544fbde781ab2f6de98809c6a8a6b553f1feef79ace06fb712ba87c3e554e227ad39426834fcd069a  0003-vendor-libc-Add-support-for-loongarch64-linux-musl.patch
ca8880cdf0c5a5e55d5b0ad6441d90d42e4a143bc8183cf1eefa8f0300e461f57ddc8bfb58547f3693c8e746f75ac6f5a89a85679e5cb43f71a27d69df520da7  0004-vendor-libc-0.2.151-Add-support-for-loongarch64-linu.patch
808e5cb5e3e0cc991ded0875e6f9cad7b72854f004ce5b626f45169ca10dc1d0d6f6b30bbe573b7daec82636edac94792522e7d9f5a13a67fd9fb0d9db1a0757  0005-vendor-compiler_builtins-Add-support-for-loongarch64.patch
54ed2846e621aea0dd42e7a1e65bdea0d6ff2dcd396770f33ee1b9a3ed33e6b36e230643e3d444dd12285f30eceed7c66a9c83fbcd23c784fa5b9785aaf37ad1  0006-vendor-openssl-src-Add-support-for-loongarch64-linux.patch
2144b8fdb6e413a51535276b320d1aa2e4d8dddc86f241360997b9fc2ea9f7450c33a5957dd54e54e3b80438316d5067482a80f692fe67ffb331c77d553b3c3a  0007-Revert-loongarch-add-frecipe-and-relax-target-featur.patch
c31fdfe8a9b3411576c75da46645cf0465b9053000a2ab49cf9b2f2733f679d6d33acbf236d67a20e14935d094a685453b7f1840180249f39d610fd0902c3125  check-rustc
"
